package com.danan.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.danan.realtime.app.BaseApp;
import com.danan.realtime.common.Constant;
import com.danan.realtime.pojo.TradeOrderBean;
import com.danan.realtime.util.SinkUtil;
import com.danan.realtime.util.TimeUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @author NanHuang
 * @Date 2023/1/26
 */
public class DwsApp_8_trade_order_window extends BaseApp {
    public static void main(String[] args) {
        new DwsApp_8_trade_order_window().init(
                5008,
                3,
                "DwsApp_8_trade_order_window",
                Constant.TOPIC_DWD_TRADE_ORDER_DETAIL
        );
    }
    @Override
    public void invoke(StreamExecutionEnvironment env, DataStreamSource<String> ds) {
        // 1 过滤数据，封装为pojo
        SingleOutputStreamOperator<TradeOrderBean> beanDs = toTradeOrderBean(ds);
        // 2 开窗聚合
        SingleOutputStreamOperator<TradeOrderBean> resultDs = windowAndAgg(beanDs);
        // 3 写入Clickhouse中
        resultDs.addSink(SinkUtil.getClickhouseSink(Constant.TOPIC_DWS_TRADE_ORDER_WINDOW,TradeOrderBean.class));
    }

    private SingleOutputStreamOperator<TradeOrderBean> windowAndAgg(SingleOutputStreamOperator<TradeOrderBean> ds) {
        // 1 创建水印策略
        WatermarkStrategy<TradeOrderBean> strategy = WatermarkStrategy.<TradeOrderBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                .withTimestampAssigner((s, l) -> s.getTs())
                .withIdleness(Duration.ofSeconds(60));
        // 2 开窗聚合
        return ds.assignTimestampsAndWatermarks(strategy)
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(new ReduceFunction<TradeOrderBean>() {
                    @Override
                    public TradeOrderBean reduce(TradeOrderBean t1, TradeOrderBean t2) throws Exception {
                        t2.setOrderUniqueUserCount(t2.getOrderUniqueUserCount() + t1.getOrderUniqueUserCount());
                        t2.setOrderNewUserCount(t2.getOrderNewUserCount() + t1.getOrderNewUserCount());
                        return t2;
                    }
                }, new AllWindowFunction<TradeOrderBean, TradeOrderBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window, Iterable<TradeOrderBean> values, Collector<TradeOrderBean> out) throws Exception {
                        TradeOrderBean result = values.iterator().next();
                        result.setStt(TimeUtil.parseDateStr(window.getStart(),true));
                        result.setEdt(TimeUtil.parseDateStr(window.getEnd(),true));
                        result.setTs(System.currentTimeMillis());
                        out.collect(result);
                    }
                });
    }

    private SingleOutputStreamOperator<TradeOrderBean> toTradeOrderBean(DataStreamSource<String> ds) {
        return ds.map(JSON::parseObject)
//                .filter(j -> j.getString("user_id") != null)
                .keyBy(j -> j.getString("user_id"))
                .process(new KeyedProcessFunction<String, JSONObject, TradeOrderBean>() {

                    private ValueState<String> flagData;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        flagData = getRuntimeContext().getState(new ValueStateDescriptor<String>("flagData", String.class));
                    }

                    @Override
                    public void processElement(JSONObject value, KeyedProcessFunction<String, JSONObject, TradeOrderBean>.Context ctx, Collector<TradeOrderBean> out) throws Exception {
                        long ts = value.getLong("ts") * 1000;
                        String currentDate = TimeUtil.parseDateStr(ts, false);
                        long uuCt = 0L;
                        long nuCt = 0L;
                        if (!currentDate.equals(flagData.value())){
                            uuCt = 1L;
                            if (flagData.value() == null){
                                nuCt = 1L;
                            }
                            flagData.update(currentDate);
                        }
                        if (uuCt == 1){
                            out.collect(
                                    TradeOrderBean.builder()
                                            .orderUniqueUserCount(uuCt)
                                            .orderNewUserCount(nuCt)
                                            .ts(ts)
                                            .build()
                            );
                        }
                    }
                });
    }
}
